// eslint-disable-next-line import/order
import otelSDK from './trace/tracing';
otelSDK.start();

import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { type Express, json } from 'express';

import { AppModule } from './app.module';
import { TraceInterceptor } from './trace/trace.interceptor';
import { TraceLogger } from './trace/trace.logger';

async function bootstrap(): Promise<void> {
  const app = (await NestFactory.create(AppModule, {
    logger: new TraceLogger(),
  }))
    .enableShutdownHooks()
    .useGlobalPipes(new ValidationPipe({ transform: true }))
    .useGlobalInterceptors(new TraceInterceptor())
    .use(json({ limit: '10mb' }));

  app.enableCors({ origin: '*' });
  (app.getHttpAdapter().getInstance() as Express).disable('x-powered-by');

  const configService = app.get(ConfigService);

  const swaggerConfig = new DocumentBuilder()
    .setTitle('IoT API')
    .addBearerAuth()
    .setDescription('设备管理平台 API')
    .setVersion(configService.get<string>('version')!)
    .build();
  const document = SwaggerModule.createDocument(app, swaggerConfig);
  SwaggerModule.setup('docs', app, document);

  const port = configService.get<number>('port')||9999;
  console.log(`Server is running on port ${port}`)
  await app.listen(port);
}

bootstrap().catch((err) => {
  console.error(err);
  process.exit(1);
});